package com.ruicar.afs.cloud.afscase.risk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCustInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCustInfoService;
import com.ruicar.afs.cloud.afscase.risk.config.DayBookResolveConfig;
import com.ruicar.afs.cloud.afscase.risk.service.DayBookResolveService;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.CustRoleEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.enums.AttachmentUniqueCodeEnum;
import com.ruicar.afs.cloud.image.enums.FileStatusEnum;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.risk.api.dto.tortoise.DayBookResolveDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author Peng Jinbo
 * @Date 2020/08/31 19:10
 */
@Service
@AllArgsConstructor
@Slf4j
public class DayBookResolveServiceImpl implements DayBookResolveService {

    private DayBookResolveConfig dayBookResolveConfig;
    private CaseCustInfoService caseCustInfoService;
    private ComAttachmentFileService comAttachmentFileService;
    private ComAttaManageService comAttaManageService;

    @Override
    public List<DayBookResolveDTO> getDayBookResolve(String applyNo) {
        List<DayBookResolveDTO> result = new ArrayList<>();
        try {
            Assert.isTrue(StrUtil.isNotBlank(applyNo),"流水解析，申请编号不可为空");
            List<CaseCustInfo> caseCustInfoList = caseCustInfoService.list(
                    Wrappers.<CaseCustInfo>lambdaQuery()
                        .eq(CaseCustInfo::getApplyNo,applyNo)
            );
            if(CollectionUtil.isNotEmpty(caseCustInfoList)) {
                StringBuffer cards = new StringBuffer();
                Map<String,CaseCustInfo> custCertNoMap = new HashMap<>();
                for (int i = 0; i < caseCustInfoList.size(); i++) {
                    CaseCustInfo customerInfo = caseCustInfoList.get(i);
                    cards.append(customerInfo.getCertNo());
                    if(i != caseCustInfoList.size()-1){
                        cards.append(",");
                    }
                    custCertNoMap.put(customerInfo.getCertNo(),customerInfo);
                }
                log.info("流水解析接口入参：{}",cards);
                JSONObject reqParam = new JSONObject();
                reqParam.put("CARD", cards.toString());
                HttpResponse response = HttpUtil.createPost(dayBookResolveConfig.getUri()).timeout(30000).body(reqParam).execute();
                if (StrUtil.isNotBlank(response.body())) {
                    JSONObject responseBody = JSONUtil.parseObj(response.body());
                    log.warn("流水解析查询结果: {}", responseBody);
                    if (responseBody.containsKey("success") && StrUtil.equals(responseBody.getStr("success"), "1")) {
                        result = JSONArray.parseArray(responseBody.getStr("data"), DayBookResolveDTO.class);
                        List<ComAttachmentFile> files = new ArrayList<>();
                        Map<String,String> roleAndFileTypeMap = new HashMap<>();
                        roleAndFileTypeMap.put(CustRoleEnum.MIANCUST.getCode(),AttachmentUniqueCodeEnum.DAY_BOOK_CUSTOMER.getCode());
                        roleAndFileTypeMap.put(CustRoleEnum.COMMONCSUT.getCode(),AttachmentUniqueCodeEnum.DAY_BOOK_SPONSOR.getCode());
                        roleAndFileTypeMap.put(CustRoleEnum.GUARANTOR.getCode(),AttachmentUniqueCodeEnum.DAY_BOOK_BOND.getCode());
                        List<String> attachmentCodeList = roleAndFileTypeMap.values().stream().collect(Collectors.toList());
                        List<ComAttachmentManagement> fileManageList = comAttaManageService.list(
                                Wrappers.<ComAttachmentManagement>lambdaQuery()
                                        .in(ComAttachmentManagement::getUniqueCode,attachmentCodeList)
                        );
                        if(CollectionUtil.isNotEmpty(fileManageList)) {
                            Map<String,ComAttachmentManagement> fileCodeMap = new HashMap<>();
                            for (ComAttachmentManagement management : fileManageList) {
                                fileCodeMap.put(management.getUniqueCode(),management);
                            }
                            for (DayBookResolveDTO dayBookResolveDTO : result) {
                                CaseCustInfo custInfo = custCertNoMap.get(dayBookResolveDTO.getCustomerIdCard());
                                String attachUniqueCode = roleAndFileTypeMap.get(custInfo.getCustRole());
                                ComAttachmentManagement management = fileCodeMap.get(attachUniqueCode);
                                ComAttachmentFile file = comAttachmentFileService.getOne(
                                        Wrappers.<ComAttachmentFile>lambdaQuery()
                                            .eq(ComAttachmentFile::getBelongNo,applyNo)
                                            .eq(ComAttachmentFile::getAttachmentCode,management.getId().toString())
                                );
                                if(Objects.isNull(file)) {
                                    file = new ComAttachmentFile();
                                    file.setBusiNo(applyNo);
                                    file.setBelongNo(applyNo);
                                    file.setAttachmentCode(Convert.toStr(management.getId()));
                                    file.setAttachmentName(management.getAttachmentName());
                                    file.setFileStatus(FileStatusEnum.STANDARD.getCode());
                                    file.setFileType("pdf");
                                    file.setHistoryVersion("0");
                                    file.setFileId(dayBookResolveDTO.getMd5());
                                    file.setUploadTime(new Date());
                                }else{
                                    file.setFileId(dayBookResolveDTO.getMd5());
                                    file.setHistoryVersion(Convert.toStr(Convert.toInt(file.getHistoryVersion(),0)+1));
                                }
                                files.add(file);
                            }
                            comAttachmentFileService.saveOrUpdateBatch(files);
                            log.info("流水解析调用成功! : {}", responseBody);
                        }else{
                            log.warn("流水解析数据持久化失败，未找到影像资料类别");
                        }
                    }
                }else{
                    log.warn("流水解析返回数据为空：{}",applyNo);
                }
            }
        } catch (Exception e) {
            log.error("流水解析接口调用异常", e);
        } finally {
            return result;
        }
    }
}
